package com.zzh.weixinsell.service.impl;

import com.zzh.weixinsell.dao.ProductInfoMapper;
import com.zzh.weixinsell.enums.ProductStatusEnum;
import com.zzh.weixinsell.enums.ResultEnum;
import com.zzh.weixinsell.exception.SellException;
import com.zzh.weixinsell.model.dto.CartDTO;
import com.zzh.weixinsell.model.pojo.ProductInfo;
import com.zzh.weixinsell.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Create by ${ZZH} on 2018/4/19
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoMapper productInfoMapper;

    @Override
    public ProductInfo findOne(String produceId) {
        return productInfoMapper.findOne(produceId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoMapper.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfo> findAll(SpringDataWebProperties.Pageable pageable) {
        return null;
    }

    @Override
    public int insertOne(String product_id, String product_name, Integer product_price, Integer product_stock, String product_description, String product_icon, Integer product_status, Integer category_type) {
        return productInfoMapper.insertOne(product_id, product_name, product_price, product_stock, product_description, product_icon, product_status, category_type);
    }

    @Override
    @Transactional
    public void increaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoMapper.findOne(cartDTO.getProductId());

            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            Integer result = productInfo.getProductStock() + cartDTO.getProductQuantity();
            productInfo.setProductStock(result);
            productInfoMapper.updateByPrimaryKey(productInfo);
        }

    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList) {
        for (CartDTO cartDTO : cartDTOList) {
            ProductInfo productInfo = productInfoMapper.findOne(cartDTO.getProductId());

            if (productInfo == null) {
                throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            Integer result = productInfo.getProductStock() - cartDTO.getProductQuantity();
            if (result < 0) {
                throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
            }
            productInfo.setProductStock(result);
            productInfoMapper.updateByPrimaryKey(productInfo);
        }
    }
}
